<template>
  <el-container class='elheight'>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              积分描述：
              <el-input v-model="selectForm.name" clearable autocomplete="off" class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            :before-close="cancel" :close-on-click-modal="false" class="custom-dialog_style">
            <el-form :model="formData"
                     :rules="rules"
                     :disabled="showOnly"
                     ref="formData">
              <el-form-item label="积分名称：" prop="name">
                <el-input v-model="formData.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="积分分类：" prop="gradeType">
                <el-select v-model="formData.gradeType" clearable placeholder="请选择">
                  <el-option label="个人" value="01"></el-option>
                  <el-option label="部门" value="02"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="编码：">
                <el-input v-model="formData.code" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="计算类型：" prop="computeType">
                <el-select v-model="formData.computeType" clearable placeholder="请选择" @change="computeTypeChangedEvt">
                  <el-option label="加" value="01"></el-option>
                  <el-option label="减" value="02"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="积分：" prop="grade">
                <el-input v-model="formData.grade" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="备注：">
                <el-input type="textarea" v-model="formData.remarks"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {findIntegral, createIntegral, updateIntegral, delIntegral} from '@/http/integralApi'
export default {
  data () {
    let reg = /^[1-9]\d{0,}/
    var checkGrade = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入积分'))
      } else {
        value = parseInt(value)
        if (!reg.test(value)) {
          return callback(new Error('请输入正确积分值'))
        } else {
          setTimeout(() => {
            callback()
          }, 1000)
        }
      }
    }
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'name', label: '描述' },
        { prop: 'gradeType', label: '积分类型', formatter: this.gradeTypeFormatter },
        { prop: 'grade', label: '积分' },
        { prop: 'remarks', label: '备注' }
      ],
      tableDada: [],
      formData: {},
      selectForm: {},
      rules: {
        name: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        computeType: [
          { required: true, message: '请选择计算类型', trigger: 'blur' }
        ],
        grade: [
          { required: true, validator: checkGrade, trigger: 'blur' }
        ],
        gradeType: [
          { required: true, message: '请选择积分类型', trigger: 'blur' }
        ]
      },
      isAddGrade: true
    }
  },
  components: {
    BtnGroup,
    AppTable
  },
  mounted () {
    this.getTableData()
  },
  methods: {
    gradeTypeFormatter (row, column) {
      let gradetypeName = row['gradeType'] === '01' ? '个人积分' : '部门积分'
      return gradetypeName
    },
    computeTypeChangedEvt (val) {
      if (val) {
        switch (val) {
          case '01':
            this.isAddGrade = true
            break
          default:
            this.isAddGrade = false
            break
        }
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          this.formData.grade = this.isAddGrade ? parseInt(this.formData.grade) : parseInt(-this.formData.grade)
          if (this.formData.id) {
            updateIntegral(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          } else {
            createIntegral(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delIntegral(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      findIntegral(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          this.formData = {}
        } else {
          let obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          this.formData.grade > 0 ? this.$set(this.formData, 'computeType', '01') : this.$set(this.formData, 'computeType', '02')
          this.isAddGrade = this.formData.grade > 0
          if (this.formData.grade < 0) this.formData.grade = -this.formData.grade
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
      } else {
        this.currentSelectedData = []
      }
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>
<style scoped>
.elheight {
  margin-left: 10px
}
</style>
